package com.sais.manage.boot.platform.acpect;

import com.sais.manage.boot.platform.exception.BusinessException;
import com.sais.manage.boot.platform.storage.IdempotentCodeStorage;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Slf4j
@Aspect
@Component
public class IdempotentAcpect {

    @Pointcut("@annotation(com.sais.manage.boot.platform.annotation.Idempotent)")
    public void idempotent() {
    }

    @Before("idempotent()")
    public void doLoginBefore(JoinPoint joinPoint) {
        // 接收到请求，记录请求内容
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String idempotent = request.getHeader("idempotent");
        if (StringUtils.isEmpty(idempotent)) {
            throw new BusinessException("idempotent 不能为空");
        }
        if (IdempotentCodeStorage.hasIdempotentCode(idempotent)) {
            throw new BusinessException("重复提交！");
        }
        IdempotentCodeStorage.setIdempotentCode(idempotent, 3L);
    }

    @AfterThrowing(pointcut = "idempotent()")
    public void doLoginAfterThrowing(JoinPoint joinPoint) {
    }

    @AfterReturning(returning = "ret", pointcut = "idempotent()")
    public void doLoginAfterReturning(Object ret) {
    }

}
